package com.lix.service.workflow.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lix.auth.filter.TokenVerificationFilter;
import com.lix.base.BaseResult;
import com.lix.mapper.LeaveMapper;
import com.lix.pojo.model.Leave;
import com.lix.service.workflow.IBusinessStatusService;
import com.lix.service.workflow.ILeaveService;
import com.lix.utils.UserUtils;
import com.lix.vo.workflow.req.LeaveReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper, Leave> implements ILeaveService {
    @Autowired
    private IBusinessStatusService businessStatusService;

    @Autowired
    private UserUtils userUtils;

    @Transactional
    public BaseResult add(Leave leave) {

        // 保存到请假业务表
        leave.setUsername(userUtils.getUsername());
        int size = baseMapper.insert(leave);
        if (size == 1) {
            // 保存到业务流程关系中间表
            businessStatusService.add(leave.getId());
        }
        return BaseResult.ok();
    }

    @Override
    public BaseResult listPage(LeaveReq req) {
        if (StringUtils.isEmpty(req.getUsername())) {
            // 当前登录用户
            req.setUsername(userUtils.getUsername());
        }
        // 创建一个分页对象
        // 使用 req 中的分页参数
        Page<Leave> page = new Page<>(req.getPageNum(), req.getPageSize());
        // 调用分页查询
        IPage<Leave> resultPage = baseMapper.getLeaveAndStatusList(page, req);
        return BaseResult.ok(resultPage);
    }

    @Override
    public BaseResult update(Leave leave) {
        if (leave == null || StringUtils.isEmpty(leave.getId())) {
            return BaseResult.error("数据不合法");
        }
        // 查询原数据
        Leave entity = baseMapper.selectById(leave.getId());
        // 拷贝新数据
        BeanUtils.copyProperties(leave, entity);
        entity.setUpdateDate(new Date());
        baseMapper.updateById(entity);
        return BaseResult.ok();
    }
}
